package com.wolf.etl.core.loadbalance;

import com.wolf.etl.core.ETLManager;
import com.wolf.etl.enumeration.INSTANCE_STATUS;
import com.wolf.etl.model.EtlInstanceModel;
import com.wolf.util.WolfSocketUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 服务器健康心跳检查
 *
 * @author sdyang
 * @date 2019/12/25 17:13
 **/
@Component
public class HeartbeatCheck {

    @Autowired
    private ETLManager etlManager;

    /**
     * 每分钟心跳检查
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void check() {

        List<EtlInstanceModel> instances = etlManager.findAllInstance();

        for (EtlInstanceModel instance : instances) {
            if (instance.getStatus() == INSTANCE_STATUS.FINISH.getValue()) {
                continue;
            }
            Boolean isRunning = WolfSocketUtils.isRunning(instance.getIp(), instance.getPort());

            // 服务器异常
            if (isRunning && instance.getStatus() == INSTANCE_STATUS.ERROR.getValue()) {
                instance.setStatus(INSTANCE_STATUS.ENABLE.getValue());
                etlManager.updateInstance(instance);
            }

            // 服务器正常
            if (!isRunning && instance.getStatus() == INSTANCE_STATUS.ENABLE.getValue()) {
                instance.setStatus(INSTANCE_STATUS.ERROR.getValue());
                etlManager.updateInstance(instance);
            }

        }

    }
}
